#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc,const char *argv[])
{
	int client_fd;
	pid_t pid;
	int ret;
	char buf[64] = "";
	struct sockaddr_in server_addr;

	client_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(client_fd == -1)
	{
		perror("fail to socket");
		return -1;
	}
	memset(&server_addr,0,sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(argv[2]));
	server_addr.sin_addr.s_addr = inet_addr(argv[1]);

	ret = connect(client_fd, (struct sockaddr *)&server_addr,sizeof(server_addr));
	if(ret == -1)
	{
		perror("fail to connect\n");
		return -1;
	}
	pid = fork();
	if(pid > 0)
	{
		while(1)
		{
			ret = recv(client_fd, buf, 64, 0);
			if(ret > 0)
			{
				printf("%s\n",buf);
				memset(buf,0,64);
			}
			else if(ret < 0)
			{
				perror("fail to recv\n");
				close(client_fd);
				return -1;
			}
			else
			{
				printf("peer exit\n");
				close(client_fd);
				return 0;
			}
		}
	}	
	else if(pid == 0)
	{
		while(1)
		{
			scanf("%s",buf);
			getchar();
			send(client_fd, buf, strlen(buf), 0);
			memset(buf,0,64);
		}
	}
	else
	{
		printf("err\n");
		return -1;
	}


	return 0;


}
